﻿Imports System.Runtime.CompilerServices
Imports Microsoft.SharePoint
Imports System.Xml

Namespace Extensions
    Public Module SPSiteExtensions

        ''' <summary>
        ''' Returns the list that is associated with a full URL, site relative URL, list name, or list GUID.
        ''' </summary>
        ''' <param name="site"></param>
        ''' <param name="value"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <Extension()> _
        Public Function TryFindList(ByVal site As SPSite, ByVal value As String) As SPList

            Using site
                If value.StartsWith("http") Then
                    Using subWeb As SPWeb = site.OpenWeb
                        Return subWeb.GetList(value)
                    End Using
                ElseIf value.StartsWith("/") Then
                    Dim wUrl As String = value.Substring(0, value.IndexOf("/Lists/") + 1)
                    Using subWeb As SPWeb = site.OpenWeb(wUrl)
                        Return subWeb.GetList(site.Url + value)
                    End Using
                ElseIf value.Contains("/") Then
                    value = "/" + value
                    Dim wUrl As String = value.Substring(0, value.IndexOf("/Lists/") + 1)
                    Using subWeb As SPWeb = site.OpenWeb(wUrl)
                        Return subWeb.GetList(site.Url + value)
                    End Using
                ElseIf IsGuid(value) Then
                    For Each subWeb As SPWeb In site.AllWebs
                        Try

                            Return subWeb.Lists.GetList(New Guid(value), False)
                            Exit For
                        Catch
                        End Try
                    Next
                Else
                    For Each subWeb As SPWeb In site.AllWebs
                        Try
                            Return subWeb.Lists.TryGetList(value)
                            Exit For
                        Catch
                        End Try
                    Next
                End If
            End Using

            Return Nothing
        End Function

    End Module
End Namespace